package com.xm;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Author：xm
 * Project：interview
 * Date：2025/8/5  18:08
 */

public class _01_SynchronizedBlock {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 执行两次synchronized(非静态)，非静态对象作用域是同一个对象，这里是两个对象分别调用，不会阻塞3秒
        executorService.execute(() -> {
            _01_SynchronizedBlock synchronizedBlock = new _01_SynchronizedBlock();
            synchronizedBlock.thisMethod();
        });
        executorService.execute(() -> {
            _01_SynchronizedBlock synchronizedBlock2 = new _01_SynchronizedBlock();
            synchronizedBlock2.thisMethod();
        });

        // 执行两次synchronized(非静态)，非静态对象的作用域是同一个对象，会阻塞3秒
        // _01_SynchronizedBlock synchronizedBlock22 = new _01_SynchronizedBlock();
        // executorService.execute(() -> {
        //     synchronizedBlock22.thisMethod();
        // });
        // executorService.execute(() -> {
        //     synchronizedBlock22.thisMethod();
        // });

        // 执行两次synchronized(静态)，静态对象作用域是全局的，锁定的是同一个静态对象，所以会阻塞
        executorService.execute(() -> {
            _01_SynchronizedBlock synchronizedBlock3 = new _01_SynchronizedBlock();
            synchronizedBlock3.classMethod();
        });
        executorService.execute(() -> {
            _01_SynchronizedBlock synchronizedBlock4 = new _01_SynchronizedBlock();
            synchronizedBlock4.classMethod();
        });

        executorService.shutdown();
    }

    private Object value = new Object();
    private static Object staticValue = new Object();

    public void thisMethod() {
        synchronized (value) {
            System.out.println("synchronized (value)加锁：" + LocalDateTime.now());
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void classMethod() {
        synchronized (staticValue) {
            System.out.println("synchronized (staticValue)加锁" + LocalDateTime.now());
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
